import React, { Suspense } from 'react'
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import { staticRoutes, IFRouteItem } from './routerConfig'
import RouteWrapper from './RouteWrapper'
import Mask from '../components/Mask/Mask'
import Loading from '../components/Loading/Loading'
import { requireLogin } from './routerUtils'

export default () => {
  // 创建路由
  const createRoute = (r: IFRouteItem) => {
    const route = (r: IFRouteItem) => {
      const ComponentItem = r.component
      return (
        <Route
          exact
          key={r.path}
          path={r.path}
          render={(props): React.ReactElement => {
            const wrapper = (
              <RouteWrapper {...{ ...props, Comp: ComponentItem, route: r }} />
            )
            const { onAuthLogin, beforeEnter } = r
            if (beforeEnter) {
              return beforeEnter(props, wrapper)
            }
            // 不需要登录校验的页面
            if (onAuthLogin) {
              return wrapper
            } else if (requireLogin(props)) {
              return wrapper
            } else {
              return <Redirect to={'/login'} />
            }
          }}
        />
      )
    }
    return route(r)
  }
  const pageFallback = (): React.ReactElement => {
    return (
      <Mask show styles={{ backgroundColor: 'transparent' }}>
        <Loading />
      </Mask>
    )
  }
  return (
    <Suspense fallback={pageFallback()}>
      <Router>
        <Switch>{staticRoutes.map((r) => createRoute(r))}</Switch>
      </Router>
    </Suspense>
  )
}
